package com.app.biz.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.app.biz.domain.BizCityIndustrialEconomics;
import com.app.biz.domain.BizManufacturingPmiComparison;
import com.app.biz.domain.excel.ExcelManufacturingPmiComparison;
import com.app.biz.domain.request.BizManufacturingPmiComparisonRequest;
import com.app.biz.mapper.BizManufacturingPmiComparisonFormalMapper;
import com.app.biz.mapper.BizManufacturingPmiComparisonMapper;
import com.app.biz.service.IBizManufacturingPmiComparisonService;
import com.app.biz.utils.MaxMinUtil;
import com.app.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 山东与全国制造业采购经理指数对比Service业务层处理
 *
 * @author SangGuangCan
 * @date 2023-12-27
 */

@Service
public class BizManufacturingPmiComparisonServiceImpl implements IBizManufacturingPmiComparisonService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final BizManufacturingPmiComparisonMapper bizManufacturingPmiComparisonMapper;

    private final BizManufacturingPmiComparisonFormalMapper bizManufacturingPmiComparisonFormalMapper;

    @Autowired
    public BizManufacturingPmiComparisonServiceImpl(BizManufacturingPmiComparisonMapper bizManufacturingPmiComparisonMapper,
            BizManufacturingPmiComparisonFormalMapper bizManufacturingPmiComparisonFormalMapper){
        this.bizManufacturingPmiComparisonMapper = bizManufacturingPmiComparisonMapper;
        this.bizManufacturingPmiComparisonFormalMapper = bizManufacturingPmiComparisonFormalMapper;
    }

    /**
     * 查询山东与全国制造业采购经理指数对比
     *
     * @param baseId 山东与全国制造业采购经理指数对比主键
     * @return 山东与全国制造业采购经理指数对比
     */
    @Override
    public BizManufacturingPmiComparison selectBizManufacturingPmiComparisonByBaseId(String baseId)
    {
        return bizManufacturingPmiComparisonMapper.selectBizManufacturingPmiComparisonByBaseId(baseId);
    }

    /**
     * 查询山东与全国制造业采购经理指数对比列表
     *
     * @param bizManufacturingPmiComparison 山东与全国制造业采购经理指数对比
     * @return 山东与全国制造业采购经理指数对比
     */
    @Override
    public List<BizManufacturingPmiComparison> selectBizManufacturingPmiComparisonList(BizManufacturingPmiComparison bizManufacturingPmiComparison)
    {
        return bizManufacturingPmiComparisonMapper.selectBizManufacturingPmiComparisonList(bizManufacturingPmiComparison);
    }

    /**
     * 新增山东与全国制造业采购经理指数对比
     *
     * @param bizManufacturingPmiComparison 山东与全国制造业采购经理指数对比
     * @return 结果
     */
    @Override
    public int insertBizManufacturingPmiComparison(BizManufacturingPmiComparison bizManufacturingPmiComparison)
    {
        bizManufacturingPmiComparison.setBaseId(IdUtil.simpleUUID());
        bizManufacturingPmiComparison.setBaseCreateTime(DateUtils.getNowDate());
        return bizManufacturingPmiComparisonMapper.insertBizManufacturingPmiComparison(bizManufacturingPmiComparison);
    }

    /**
     * 修改山东与全国制造业采购经理指数对比
     *
     * @param bizManufacturingPmiComparison 山东与全国制造业采购经理指数对比
     * @return 结果
     */
    @Override
    public int updateBizManufacturingPmiComparison(BizManufacturingPmiComparison bizManufacturingPmiComparison)
    {
        return bizManufacturingPmiComparisonMapper.updateBizManufacturingPmiComparison(bizManufacturingPmiComparison);
    }

    /**
     * 批量删除山东与全国制造业采购经理指数对比
     *
     * @param baseIds 需要删除的山东与全国制造业采购经理指数对比主键
     * @return 结果
     */
    @Override
    public int deleteBizManufacturingPmiComparisonByBaseIds(String[] baseIds)
    {
        return bizManufacturingPmiComparisonMapper.deleteBizManufacturingPmiComparisonByBaseIds(baseIds);
    }

    /**
     * 删除山东与全国制造业采购经理指数对比信息
     *
     * @param baseId 山东与全国制造业采购经理指数对比主键
     * @return 结果
     */
    @Override
    public int deleteBizManufacturingPmiComparisonByBaseId(String baseId)
    {
        return bizManufacturingPmiComparisonMapper.deleteBizManufacturingPmiComparisonByBaseId(baseId);
    }

    /**
     * 导入Excel数据
     *
     * @param truePath Excel的路径
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importManufacturingPmiComparison(String truePath) {
        List<BizManufacturingPmiComparison> list = new ArrayList<>();
        EasyExcel.read(truePath, ExcelManufacturingPmiComparison.class,new PageReadListener<ExcelManufacturingPmiComparison>(dataList -> {
            for(ExcelManufacturingPmiComparison excelItem : dataList){
                logger.info("读出来的数据：年月：{},全国：{},山东：{}",excelItem.getYearMonth(),excelItem.getNationwide(),excelItem.getShandong());
                BizManufacturingPmiComparison item = new BizManufacturingPmiComparison();
                item.setBaseId(IdUtil.simpleUUID());
                item.setNationwide(excelItem.getNationwide());
                item.setShandong(excelItem.getShandong());
                item.setBaseCreateTime(DateUtils.getNowDate());
                item.setRemark(excelItem.getRemark());
                item.setYearMonth(DateUtil.parse(excelItem.getYearMonth(),"yyyy.MM"));
                list.add(item);
            }
        })).sheet().doRead();

        if(!list.isEmpty()){
            bizManufacturingPmiComparisonMapper.batchInsertManufacturingPmiCompariso(list);
        }
    }

    /**
     * 查询指定日期前一年的数据
     *
     * @param bizManufacturingPmiComparisonRequest 查询的参数
     * @return 查询的结果
     */
    @Override
    public List<BizManufacturingPmiComparison> getDataOneYearBeforeSpecificDate(BizManufacturingPmiComparisonRequest bizManufacturingPmiComparisonRequest) {
        String specifiedDateStr = bizManufacturingPmiComparisonRequest.getDates();
        /** 根据今年的日期获取上一年的日期 */
        DateTime nextYearDate = DateUtil.offsetMonth(DateUtil.parse(specifiedDateStr, "yyyy年MM月"), -12);
        bizManufacturingPmiComparisonRequest.setNextYearDate(DateUtil.format(nextYearDate,"yyyy-MM-dd"));

        //将原来传入的yyyy年MM月格式转成yyyy-MM-dd格式
        DateTime specifiedDate = DateUtil.parse(specifiedDateStr, "yyyy年MM月");
        bizManufacturingPmiComparisonRequest.setDates(DateUtil.format(specifiedDate,"yyyy-MM-dd"));

        List<BizManufacturingPmiComparison> result = bizManufacturingPmiComparisonMapper.getDataOneYearBeforeSpecificDate(bizManufacturingPmiComparisonRequest);
        return result;
    }

    /**
     * <p>
     * 查询数据库中数据的日期(year_month字段)并进行去重复操作<br/>
     * 主要用于的是APP端左上角的日期过滤
     * </p>
     *
     * @return 日期的数组
     */
    @Override
    public List<String> getUniqueDatesFromDatabase() {
        List<String> uniqueDatesFromDatabase = bizManufacturingPmiComparisonMapper.getUniqueDatesFromDatabase();
        if(!uniqueDatesFromDatabase.isEmpty()){
            //Mysql中去重关键字和排序不能对同一字段同时使用，这里通过代码来去重
            return uniqueDatesFromDatabase.stream().distinct().collect(Collectors.toList());
        }
        return uniqueDatesFromDatabase;
    }

    /**
     * 查询指定日期前一年的数据图表
     *
     * @param bizManufacturingPmiComparisonRequest 传来的数据
     * @return 查询的结果
     */
    @Override
    public Map<String,Object> getDataOneYearBeforeSpecificDateEcharts(BizManufacturingPmiComparisonRequest bizManufacturingPmiComparisonRequest) {
        String specifiedDateStr = bizManufacturingPmiComparisonRequest.getDates();
        /* 根据今年的日期获取上一年的日期 */
        DateTime nextYearDate = DateUtil.offsetMonth(DateUtil.parse(specifiedDateStr, "yyyy年MM月"), -12);
        bizManufacturingPmiComparisonRequest.setNextYearDate(DateUtil.format(nextYearDate,"yyyy-MM-dd"));

        //将原来传入的yyyy年MM月格式转成yyyy-MM-dd格式
        DateTime specifiedDate = DateUtil.parse(specifiedDateStr, "yyyy年MM月");
        bizManufacturingPmiComparisonRequest.setDates(DateUtil.format(specifiedDate,"yyyy-MM-dd"));

        List<BizManufacturingPmiComparison> result = bizManufacturingPmiComparisonMapper.getDataOneYearBeforeSpecificDate(bizManufacturingPmiComparisonRequest);

        List<Double> shanDongList = new ArrayList<>();
        List<Double> nationwideList = new ArrayList<>();
        List<String> xList = new ArrayList<>();

        /* 通过这个集合判断是否需要在月上显示年份 */
        List<Double> allDoubleValue = new ArrayList<>();

        for(BizManufacturingPmiComparison item : result){
            if(StrUtil.isBlank(item.getNationwide()) || StrUtil.isBlank(item.getShandong())){
                throw new RuntimeException(String.format("%s月份中出现全国数据或山东数据为空的情况,请核查",DateUtil.format(item.getYearMonth(),"yyyy年MM月")));
            }
            shanDongList.add(Double.valueOf(item.getShandong()));
            nationwideList.add(Double.valueOf(item.getNationwide()));

            allDoubleValue.add(Double.valueOf(item.getShandong()));
            allDoubleValue.add(Double.valueOf(item.getNationwide()));

            xList.add(DateUtil.format(item.getYearMonth(),"MM月"));
        }

        Map<String,Object> resultMap = new HashMap<>(16);
        if(allDoubleValue.isEmpty()){
            resultMap.put("max",0);
            resultMap.put("min",0);
        }else{
            double[] allData = allDoubleValue.stream().mapToDouble(Double::doubleValue).toArray();
            int[] maxAndMin = MaxMinUtil.calculateYAxisRange(allData);
            resultMap.put("max",maxAndMin[0]);
            resultMap.put("min",maxAndMin[1]);
        }
        resultMap.put("shandong",shanDongList);
        resultMap.put("nationwideList",nationwideList);
        resultMap.put("xList",xList);

        return resultMap;
    }

    /**
     * <p>
     *     将临时表中的数据转移到正式表中
     * </p>
     * @return 是否转移成功
     */
    @Override
    public boolean transferDataInOneClick() {
        try{
            /* 查询数据库中最新的一条日期 */
//            String latestDateStr = bizManufacturingPmiComparisonMapper.getLatestDateData();
//            BizManufacturingPmiComparison params = new BizManufacturingPmiComparison();
//            params.setYearMonth(DateUtils.parseDate(latestDateStr,"yyyy-MM-dd"));

            List<BizManufacturingPmiComparison> result = bizManufacturingPmiComparisonMapper.selectBizManufacturingPmiComparisonAllData();

            int count = 0;
            List<BizManufacturingPmiComparison> list = new ArrayList<>();
            for(BizManufacturingPmiComparison item : result){
                item.setBaseCreateTime(DateUtils.getNowDate());
                list.add(item);
                count++;
                if(count >= 100){
                    bizManufacturingPmiComparisonFormalMapper.batchInsertManufacturingPmiCompariso(list);
                    list.clear();
                }
            }

            if(!list.isEmpty()){
                bizManufacturingPmiComparisonFormalMapper.batchInsertManufacturingPmiCompariso(list);
                list.clear();
            }
            return true;
        }catch (Exception e){
            logger.error("未知错误:{}",e.getMessage());
            return false;
        }
    }

    /**
     * <p>
     * 清空所有的山东与全国制造业采购经理指数对比数据
     * </p>
     *
     * @return
     */
    @Override
    public void clearAllTableData() {
        bizManufacturingPmiComparisonMapper.clearAllTableData();
    }
}
